<template>
  <div id="majortab">
    <div class="contaier f14">
      <div class="item-box df" style="align-items: flex-start">
        <div class="item-title">专业类型</div>
        <div style="flex: 1">
          <div class="df">
            <div class="df" style="flex-wrap: wrap">
              <div
                class="curr all-item"
                @click="handleClickAll"
                :class="{ active: isActive == -1 }"
              >
                不限({{ allChildCount }})
              </div>
              <div
                class="tabs curr"
                :class="{ active: isActive == index }"
                v-for="(item, index) in majorDataList"
                style="margin-left: 0"
                :key="item.id"
                @click="handleIsChil(item, index)"
              >
                {{ item.name }}({{ item.majors.length }})
              </div>
            </div>
          </div>
          <!-- 专业优先下级 -->
          <div class="df" style="flex-wrap: wrap" v-show="majorChildren.length">
            <div
              class="tabs curr"
              style="margin-left: 0"
              :class="isTagsSelectAll()"
              @click="handleSelectAll"
            >
              全部
            </div>
            <div
              @click="handleMajorClick(item, index)"
              class="curr chiltabs"
              style="margin: 10px 45px 10px 0"
              v-for="(item, index) in majorChildren"
              :key="item.in"
              :class="isTagActive(item)"
            >
              {{ item.name }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="df" style="position: relative; margin: 10px 10px 0 0">
      <div class="f14" style="color: #9b9b9b">我的关注：</div>
      <el-select
        v-model="majorSearch"
        @change="handleMajorChange"
        filterable
        remote
        no-match-text="无数据"
        no-data-text="无数据"
        reserve-keyword
        loading-text="加载中..."
        placeholder="请输入意向专业"
        :remote-method="remoteMajorMethod"
        :loading="searchLoading"
        style="width: 240px"
      >
        <el-option
          v-for="item in majorOptions"
          :key="item.code"
          :label="item.name"
          :value="item.code + '/' + item.name"
        />
      </el-select>
      <el-icon class="icon-search"><Search /></el-icon>
    </div>
  </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue';
import { ref, watch } from 'vue';
import bus from '../../utils/bus';
import { getSearchMajor } from '@/api/selectSubject/subject';
import store from '@/store';

const majorSearch = ref('');

const props = defineProps({
  majorDataList: {
    type: Object,
    default: () => {},
  },
});

const emits = defineEmits([
  'handleHistoryList',
  'handleClearAll',
  'updateMajorHistortList',
]);

const searchLoading = ref(false);
const majorOptions = ref([]);
const handleMajorChange = (data) => {
  const [typeCode, name] = data.split('/');
  handleMajorClick({
    code: typeCode,
    name: name,
  });
  bus.emit('updateMajorHistortList', data);
};

const remoteMajorMethod = (searchdata) => {
  let requestData = {
    level: 2,
    search: searchdata,
  };
  if (searchdata) {
    fetchSearchMajor(requestData);
  } else {
    return;
  }
};
const fetchSearchMajor = (data) => {
  getSearchMajor(data).then((res) => {
    if (res.data.code == 20000) {
      majorOptions.value = res.data.data;
    }
  });
};

const isActive = ref(-1);
const majorChildren = ref([]);

const handleIsChil = (item, index) => {
  majorChildren.value = item.majors;
  currentType.value = item.code;
  isActive.value = index;
};
const handleSelectAll = () => {
  selectedMajorGroup.value[currentType.value] = props.majorDataList
    .find((v) => v.code == currentType.value)
    .majors.map((v) => getTypeCode(v.code).code);
  emits('handleHistoryList', {
    type: 2,
    majorType: currentType.value,
    list: props.majorDataList
      .find((v) => v.code == currentType.value)
      .majors.map((v) => {
        const item = getTypeCode(v.code);
        return {
          majorType: item.type,
          code: item.code,
          name: v.name,
        };
      }),
  });
  bus.emit('updateMajorList', {
    type: 2,
    majorType: currentType.value,
    list: props.majorDataList
      .find((v) => v.code == currentType.value)
      .majors.map((v) => {
        const item = getTypeCode(v.code);
        return {
          majorType: item.type,
          code: item.code,
          name: v.name,
          codes: item.type + item.code,
        };
      }),
  });
};

const handleClickAll = () => {
  emits('handleClearAll');
  bus.emit('updateMajorListAll');
  majorChildren.value = [];
  isActive.value = -1;
  // 取消所有选项的高亮状态
  for (let type in selectedMajorGroup.value) {
    selectedMajorGroup.value[type] = [];
  }
};

const getTypeCode = (data) => {
  return {
    type: data.slice(0, 2),
    code: data.slice(2, 4),
  };
};

const selectedMajorGroup = ref({});
const isTagActive = (data) => {
  const { type, code } = getTypeCode(data.code);
  if (selectedMajorGroup.value[type] && selectedMajorGroup.value[type].length) {
    const group = selectedMajorGroup.value[type];
    const isExist = group.find((v) => v === code);
    return isExist ? 'active' : '';
  } else {
    return '';
  }
};

const currentType = ref('');
const isTagsSelectAll = () => {
  if (!props.majorDataList || currentType.value == '') {
    return;
  }
  const allCodes = props.majorDataList
    .find((v) => v.code == currentType.value)
    .majors.map((v) => v.code);
  const selectCodes = selectedMajorGroup.value[currentType.value] || [];
  if (allCodes.length == selectCodes.length) {
    return 'active';
  }
  return '';
};

// 01type 02code
const handleMajorClick = (item) => {
  const { type, code } = getTypeCode(item.code);
  // getItemFromMajor(type,code)
  currentType.value = type;
  // 是不是数组
  if (selectedMajorGroup.value[type] && selectedMajorGroup.value[type].length) {
    // 是否存在
    let group = selectedMajorGroup.value[type];
    const isExist = group.find((v) => v === code);
    if (isExist) {
      // 如果找到了 则为删除
      group = group.filter((v) => v != isExist);
      emits('handleHistoryList', {
        type: 0,
        majorType: type,
        code: code,
        name: item.name,
      });
      bus.emit('updateMajorList', {
        type: 0,
        majorType: type,
        code: code,
        name: item.name,
      });
    } else {
      group.push(code);
      emits('handleHistoryList', {
        type: 1,
        majorType: type,
        code: code,
        name: item.name,
      });
      bus.emit('updateMajorList', {
        type: 1,
        majorType: type,
        code: code,
        name: item.name,
      });
    }
    selectedMajorGroup.value[type] = group;
  } else {
    // 不是数组 首次添加的时候
    selectedMajorGroup.value[type] = [code];
    emits('handleHistoryList', {
      type: 1,
      majorType: type,
      code: code,
      name: item.name,
    });
    bus.emit('updateMajorList', {
      type: 1,
      majorType: type,
      code: code,
      name: item.name,
    });
  }
  store.commit('znxk/set_filterMarjorList', selectedMajorGroup.value);
};

const allChildCount = ref(0);
watch(
  () => props.majorDataList,
  (newValue) => {
    let count = 0;
    newValue.forEach((v) => {
      count += v.childCount;
    });
    allChildCount.value = count;
  },
);
defineExpose({
  handleMajorClick,
});
</script>

<style lang="scss" scoped>
#majortab {
  .item-title {
    width: 100px;
    margin: 10px 0;
    color: #9b9b9b;
  }
  .item-box {
    margin: 10px 0;
  }
  .tabs {
    // width: 70px;
    margin: 10px 10px;
    padding: 0 10px;
    &:hover {
      color: var(--color-text);
    }
  }
  .chiltabs,
  .all-item {
    margin-right: 10px;
    padding: 0 10px;
    &:hover {
      color: var(--color-text);
    }
  }

  .filter-item {
    background: #fff;
    border: 1px solid #e6e6e6;
    border-radius: 4px;
    font-size: 14px;
    line-height: 32px;
    height: 32px;
    margin: 4px;
    padding: 0 10px;
  }
}
.active {
  border: 1px solid var(--color-text);
  border-radius: 3px;
  color: var(--color-text);
}
.icon-search {
  position: absolute;
  top: 8px;
  left: 80px;
}
:deep(.el-select__wrapper) {
  padding-left: 30px;
}
</style>
